﻿using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DestopIcon
{
    public partial class HiddenForm : Form
    {
        public HiddenForm()
        {
            InitializeComponent();
        }

        //发生设备变动
        private const int WM_DEVICECHANGE = 0x0219;

        //系统检测到一个新设备
        private const int DBT_DEVICEARRIVAL = 0x8000;

        //系统完成移除一个设备
        private const int DBT_DEVICEREMOVECOMPLETE = 0x8001;

        //逻辑卷标
        private const int DBT_DEVTYP_VOLUME = 0x00000002;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_DEVICECHANGE:
                    switch (m.WParam.ToInt32())
                    {
                        case DBT_DEVICEARRIVAL:
                            int devType = Marshal.ReadInt32(m.LParam, 4);
                            if (devType == DBT_DEVTYP_VOLUME)
                            {
                                var vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));

                                MessageBox.Show(vol.dbcv_unitmask.ToString("x"));
                            }
                            break;
                        case DBT_DEVICEREMOVECOMPLETE:

                            MessageBox.Show("Removal");

                            break;
                    }

                    break;
            }

            base.WndProc(ref m);
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;

        public int dbcv_devicetype;

        public int dbcv_reserved;

        public int dbcv_unitmask;
    }

}


